package com.hjjt.baselib.util

import android.graphics.Bitmap

/**
 * @ProjectName: IntelligentTerminal
 * @Package: com.hjjt.baselib.util
 * @ClassName: ImageUtil
 * @Description:
 * @Author: 孙浩
 * @CreateDate: 2022/8/4 11:40
 */
object ImageUtil {
    /**
     * 彩图转换成灰色图片
     *
     * @param img
     * @return
     */
    fun convertGreyImg(img: Bitmap): Bitmap {
        val width = img.width //获取位图的宽
        val height = img.height //获取位图的高
        val pixels = IntArray(width * height) //通过位图的大小创建像素点数组
        img.getPixels(pixels, 0, width, 0, 0, width, height)
        val alpha = 0xFF shl 24
        for (i in 0 until height) {
            for (j in 0 until width) {
                var grey: Int
                grey = if (pixels[width * i + j] == 0) {
                    continue
                } else pixels[width * i + j]
                val red = grey and 0x00FF0000 shr 16
                val green = grey and 0x0000FF00 shr 8
                val blue = grey and 0x000000FF
                grey =
                    (red.toFloat() * 0.44 + green.toFloat() * 0.45 + blue.toFloat() * 0.11).toInt()
                grey = alpha or (grey shl 16) or (grey shl 8) or grey
                pixels[width * i + j] = grey
            }
        }
        //创建空的bitmap时，格式一定要选择ARGB_4444,或ARGB_8888,代表有Alpha通道，RGB_565格式的不显示灰度
        val result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444)
        result.setPixels(pixels, 0, width, 0, 0, width, height)
        return result
    }
}